package de.hwr.sudokuspielehr.ui.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import de.hwr.sudokuspielehr.data.Sudoku;
import de.hwr.sudokuspielehr.ui.UserInterface;
import de.hwr.sudokuspielehr.ui.component.SudokuCellPanel;

/**
 * 
 * @author J. Reischauer
 * 
 */
public class ClearButtonListener implements ActionListener {

	/**
	 * UserInterface instance.
	 */
	UserInterface ui;

	/**
	 * Constructor of clear button listener. Needs the UserInterface instance to
	 * determine, which of the cells was clicked last.
	 * 
	 * @param pUi
	 *            UserInterface instance
	 */
	public ClearButtonListener(UserInterface pUi) {
		ui = pUi;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		SudokuCellPanel lastClicked = ui.getLastClicked();
		if (lastClicked != null) {
			int deletedNumber = lastClicked.getNumber();
			boolean[] possibleNumbers = lastClicked.getPossibleNumbers();
			lastClicked.clear();
			ui.getSudoku().setCell(lastClicked.getIndex(), Sudoku.EMPTY_CELL_VALUE);

			if (deletedNumber != Sudoku.EMPTY_CELL_VALUE) {
				ui.setStatus(deletedNumber + " entfernt.");
			} else if (possibleNumbers != null) {
				ui.setStatus("Hilfszahlen entfernt.");
			}
		}

		if (ui.isInCreatorMode()) {
			if (ui.containsErrorInCreatorMode()) {
				if (!ui.getSudoku().containsErrors()) {
					for (SudokuCellPanel scp : ui.getCellPanels()) {
						if (scp.getComponentCount() == 1) {
							scp.getComponent(0).setForeground(null);
						}
					}
					ui.setContainsErrorInCreatorMode(false);
					ui.blockNumberButtons(false);
				}
			}
		}
	}
}
